package cn.sh.yhk;

import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class FeignConfiguration {


    @Bean
    public Feign.Builder feignBuilder() {
        return Feign.builder().requestInterceptor(new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                requestTemplate.header("auth", "false");
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    String token = request.getHeader("token");
                    if (!StringUtils.isEmpty(token)) {
                        requestTemplate.header("token", token);
                    }
                    requestTemplate.header(HttpHeaders.COOKIE, request.getHeader(HttpHeaders.COOKIE));
                }

            }
        });
    }
    //implements RequestInterceptor {
//    @Override
//    public void apply(RequestTemplate requestTemplate) {
//        Map<String, String> headers = getHeaders(getHttpServletRequest());
//        for (String headerName : headers.keySet()) {
//            requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
//        }
//    }
//
//    private HttpServletRequest getHttpServletRequest() {
//        try {
//            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//
//    private Map<String, String> getHeaders(HttpServletRequest request) {
//        Map<String, String> map = new LinkedHashMap<>();
//        Enumeration<String> enumeration = request.getHeaderNames();
//        while (enumeration.hasMoreElements()) {
//            String key = enumeration.nextElement();
//            String value = request.getHeader(key);
//            map.put(key, value);
//        }
//        return map;
//    }
}
